<template>
  <div class="sign-page">
    <div class="center-wrapper">
      <div class="logo-wrapper">
        <img class="logo-img" :src="imgSrc" alt="">
      </div>
      <div class="center-container" v-show="!emailConfirmShow">
        <div class="sign-in-wrapper" v-show="signInShow">
          <form class="sign-in-content" action="">
            <input type="text" class="sign-in-name input" placeholder="请输入用户名" v-model="signInUserName" v-focus="signInUserNameFocus">
            <input type="password" class="sign-in-password input" placeholder="请输入密码" v-model="signInPwd" v-focus="signInPwdFocus" @keyup.enter="signInSubmitHandler">
            <g-button class="sign-in-submit submit" type="primary" :loading="signInLoading" @click="signInSubmitHandler">{{ signInLoading ? '登录中...' : '登录' }}
            </g-button>
          </form>
        </div>
        <div class="register-wrapper" v-show='registerShow'>
          <div class="register-content">
            <input type="text" class="register-name input" placeholder="邮箱" v-model="registerUserName" v-focus="registerUserNameFocus" @blur="checkUserName" :class="{'wrong-input': emptyUserName || wrongUserName}">
            <p class="tip" v-show="emptyUserName">邮箱不能为空</p>
            <p class="tip" v-show="wrongUserName">请输入正确的邮箱地址</p>
            <input type="password" class="register-password input" placeholder="密码" v-model="registerPwd1" v-focus="registerPwd1Focus" @blur="checkPwd" :class="{'wrong-input': emptyPwd || wrongPwd}">
            <p class="tip" v-show="emptyPwd">密码不能为空</p>
            <p class="tip" v-show="wrongPwd">密码至少6位</p>
            <input type="password" class="register-password2 input" placeholder="再次输入密码" v-model="registerPwd2" v-focus="registerPwd2Focus" :class="{'wrong-input': !samePwd}">
            <p class="tip" v-show="!samePwd">两次输入密码不一致</p>
            <div class="verification-wrapper">
              <div class="verification-item">
                <input type="text" class="verification-input" placeholder="验证码" v-model="registerCaptcha" v-focus="registerCaptchaFocus">
              </div>
              <div class="verification-item">
                <a class="verification-code">
                  <img class="img-captcha" :src="src" @click="changeCaptcha">
                </a>
              </div>
            </div>
            <div class="agreement-wrapper">
              <span><input type="checkbox" v-model="registerCheckBox" v-focus="registerCheckBoxFocus"></span>
              我已经阅读并同意
              <a href="//geohey.com/privacy" target="_blank">隐私政策</a>
              和
              <a href="//geohey.com/terms" target="_blank">服务条款</a>
            </div>
            <input type="button" class="register-submit submit" value="注册" :class="{'disabled': !registerSubmit}" @click="registerSubmitHandler">
          </div>
        </div>
        <div class="find-pwd-wrapper" v-show="findPwdShow">
          <div class="find-pwd-content">
            <input type="text" class="input" placeholder="请输入账户邮箱" v-model="findEmail" v-focus="findEmailFocus">
            <div class="verification-wrapper">
              <div class="verification-item">
                <input type="captcha" class="verification-input" placeholder="验证码" v-model="findCaptcha" v-focus="findCaptchaFocus">
              </div>
              <div class="verification-item">
                <a class="verification-code">
                  <img class="img-captcha" :src="src" @click="changeCaptcha">
                </a>
              </div>
            </div>
            <input type="button" class="submit" :value="findSubmitText" @click="findPwdSubmit" :class="{'disabled': !findBtnAble}">
          </div>
          <a class="back-to-sign-in" @click="findPwdToggle">立即登录</a>
        </div>
        <div class="link-to-register" v-show="signInShow || registerShow">
          <!-- <a class="find-pwd" @click='findPwdToggle' v-show="signInShow">忘记密码</a> -->
          <!-- <a  class="link-toggle" @click="signToggle" >{{signInShow? '立即注册':'立即登录'}}</a> -->
        </div>
      </div>
      <div class="email-confirm-wrapper" v-show="emailConfirmShow">
        <div class="email-confirm-content">
          <p class="email-confirm-text">您的账户尚未激活。请登录注册邮箱，按照GeoHey邮件提示激活账户。如果未收到邮件，请点击下面按钮重新发送账户激活邮件。</p>
          <div class="btn-wrapper">
            <g-button class="btn-send-email" type="warning" @click="sendEmail" :class="{'disabled': !sendEmailActive}">发送激活邮件</g-button>
          </div>
        </div>
      </div>
    </div>
    <div style="width:100%;" class="footer-wrapper">
      Copyright 2019 All rights reserved 宁波市测绘设计研究院 版权所有
    </div>
  </div>
</template>
<script>
import GButton from "@/components/common/g-button";
import axios from "axios";
import qs from "qs";
import SHA1 from "crypto-js/sha1";
import config from "@/config/tjConfig.js";

let axiosInstance = axios.create({
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  withCredentials: true
});
let instance = axios.create();
let regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
let regPwd = /^.{6,}$/;

export default {
  name: "sign",
  data() {
    return {
      signInShow: true,
      registerShow: false,
      findPwdShow: false,
      emailConfirmShow: false,
      src: "//geohey.com/s/captcha/gen",
      signInUserName: "",
      signInPwd: "",
      signInPwdFocus: false,
      signInUserNameFocus: true,
      registerUserName: "",
      registerPwd1: "",
      registerPwd2: "",
      registerCaptcha: "",
      registerCheckBox: false,
      registerUserNameFocus: false,
      registerPwd1Focus: false,
      registerPwd2Focus: false,
      registerCaptchaFocus: false,
      registerCheckBoxFocus: false,
      findEmail: "",
      findCaptcha: "",
      findEmailFocus: false,
      findCaptchaFocus: false,
      findSubmitText: "找回密码",
      emailRegister: "",
      sendEmailActive: true,
      emptyUserName: false,
      emptyPwd: false,
      wrongPwd: false,
      wrongUserName: false,
      notSamePwd: false,
      signInLoading: false,
      imgSrc: ""
    };
  },
  directives: {
    focus: {
      inserted: function(el, { value }) {
        if (value) {
          el.focus();
        }
      }
    }
  },
  mounted() {
    let url = window.location.href;
    let a = url.split("?")[1];
    if (a) {
      let b = a.split("&");
      let params = new Array();
      for (let i = 0; i < b.length; i++) {
        let c = b[i].split("=")[1];
        params.push(c);
      }
      if (params.indexOf("signup") > -1) {
        this.signInShow = false;
        this.registerShow = true;
      }
    }

    window.setTimeout(() => {
      if (
        window["page"] &&
        window["page"].login_logo &&
        window["page"].login_logo !== ""
      ) {
        this.imgSrc = window["page"].login_logo;
      } else {
        this.imgSrc = require("../../../static/img/ningbo_logo.jpg");
      }
    });
  },
  computed: {
    registerSubmit() {
      return (
        this.registerUserName &&
        this.registerPwd1 &&
        this.registerPwd2 &&
        this.registerCaptcha.length === 5 &&
        this.registerCheckBox &&
        !this.emptyUserName &&
        !this.emptyPwd &&
        !this.wrongPwd &&
        !this.wrongUserName &&
        !this.notSamePwd
      );
    },
    findBtnAble() {
      return this.findEmail && this.findCaptcha.length === 5;
    },
    samePwd() {
      return this.registerPwd1 === this.registerPwd2;
    }
  },
  methods: {
    checkUserName() {
      if (this.trim(this.registerUserName).length === 0) {
        this.registerUserNameFocus = true;
        this.emptyUserName = true;
        this.wrongUserName = false;
        return;
      } else {
        this.emptyUserName = false;
      }
      if (!regEmail.test(this.registerUserName)) {
        this.signInUserNameFocus = true;
        this.wrongUserName = true;
        this.emptyUserName = false;
        return;
      } else {
        this.wrongUserName = false;
      }
    },
    checkPwd() {
      if (this.trim(this.registerPwd1).length === 0) {
        this.registerPwd1Focus = true;
        this.emptyPwd = true;
        this.wrongPwd = false;
        return;
      } else {
        this.emptyPwd = false;
      }
      if (!regPwd.test(this.registerPwd1)) {
        this.registerPwd1Focus = true;
        this.wrongPwd = true;
        this.emptyPwd = false;
      } else {
        this.wrongPwd = false;
      }
    },
    checkPwd2() {
      if (!this.emptyPwd && !this.wrongPwd) {
        if (this.registerPwd1 !== this.registerPwd2) {
          this.registerPwd2Focus = true;
          this.notSamePwd = true;
        } else {
          this.notSamePwd = false;
        }
      }
    },
    signInSubmitHandler() {
      if (this.trim(this.signInUserName).length === 0) {
        this.signInUserNameFocus = true;
        this.showErr("请输入用户名");
        return;
      } else if (this.signInPwd === 0) {
        this.showErr("请输入密码");
        return;
      }
      //this.signInUserName = this.signInUserName + '@tjism';
      // else if( !regEmail.test( this.signInUserName ) ){
      //     this.signInUserNameFocus = true;
      //     this.showErr( '请输入正确的邮箱地址' );
      //     return
      // }

      this.signInLoading = true;
      let hashPassword = SHA1(this.signInPwd).toString();
      let params = {
        email: this.signInUserName + "@ningbo.com",
        //email: this.signInUserName,
        hash_password: hashPassword
      };

      //
      let go = this.getQueryParameter("go");
      go = !go ? "" : go;
      //
      axiosInstance
        .post(`${config.host}/op/sign?go=` + go, qs.stringify(params))
        .then(res => {
          if (res.data.code === 1) {
            this.showErr(res.data.msg);
          } else if (res.data.code === 2) {
            this.emailRegister = res.data.email;
            this.confirmEmail();
          } else {
            var i = res.data.data;
            if (!i) {
              //location.href = "/";
              location.href = config.data_show_host;
            } else {
              location.href = i;
            }
          }
          this.signInLoading = false;
        })
        .catch(() => {
          this.signInLoading = false;
          this.showErr("登录失败");
        });
    },
    registerSubmitHandler() {
      if (this.registerCheckBox === false) {
        this.registerCheckBoxFocus = true;
        this.showErr("请同意许可");
        return;
      } else if (this.registerCaptcha.length !== 5) {
        this.registerCaptchaFocus = true;
        this.showErr("请输入正确的验证码");
        return;
      }
      let hashPwd1 = SHA1(this.registerPwd1).toString();
      let hashPwd2 = SHA1(this.registerPwd1).toString();
      let registerParams = {
        email: this.registerUserName,
        hash_password1: hashPwd1,
        hash_password2: hashPwd2,
        captcha: this.registerCaptcha
      };
      axiosInstance
        .post(
          `${config.host}/op/sign?mode=signup`,
          qs.stringify(registerParams)
        )
        .then(res => {
          if (res.data.code == 1) {
            this.showErr(res.data.msg);
            this.changeCaptcha();
          } else if (res.data.code == 0) {
            this.showInfo(res.data.msg);
            this.signToggle();
          }
        })
        .catch(() => {
          this.changeCaptcha();
        });
    },
    findPwdSubmit() {
      if (this.trim(this.findEmail).length === 0) {
        this.findEmailFocus = true;
        this.showErr("请输入邮箱");
        return;
      } else if (this.findCaptcha.length !== 5) {
        this.findCaptchaFocus = true;
        this.showErr("请输入正确的验证码");
        return;
      }
      let findParams = {
        email: this.findEmail,
        captcha: this.findCaptcha
      };
      axiosInstance
        .post("/op/forget_pwd", qs.stringify(findParams))
        .then(res => {
          if (res.data.length > 0) {
            this.showErr(res.data);
            this.changeCaptcha();
          } else {
            this.showInfo("已发送重置邮件到账号邮箱");
            this.findSubmitText = "重置链接已发送到邮箱";
            this.findBtnAble = false;
          }
        })
        .catch(() => {
          this.changeCaptcha();
        });
    },
    sendEmail() {
      this.sendEmailActive = false;
      instance
        .post("/op/confirm?email=" + this.emailRegister)
        .then(res => {
          if (res.data.code == 0) {
            this.showInfo("邮件已发送");
          } else {
            this.showErr(res.data.msg);
          }
          this.sendEmailActive = true;
          setTimeout(function() {
            location.href = "/sign.html";
          }, 3000);
        })
        .catch((xhr, status, error) => {
          this.showErr("邮件发送失败");
          this.sendEmailActive = true;
        });
    },
    signToggle() {
      if (this.signInShow) {
        this.changeCaptcha();
        this.registerUserName = "";
        this.registerPwd2 = "";
        this.registerPwd1 = "";
        this.registerCheckBox = false;
        this.registerCaptcha = "";
        this.emptyUserName = false;
        this.emptyPwd = false;
        this.wrongPwd = false;
        this.wrongUserName = false;
        this.notSamePwd = false;
      } else {
        this.signInUserName = "";
        this.signInPwd = "";
        this.signInLoading = false;
      }
      this.signInShow = !this.signInShow;
      this.registerShow = !this.registerShow;
    },
    findPwdToggle() {
      this.changeCaptcha();
      this.signInShow = !this.signInShow;
      this.findPwdShow = !this.findPwdShow;
      this.findEmail = "";
      this.findCaptcha = "";
      this.signInUserName = "";
      this.signInPwd = "";
      this.signInLoading = false;
    },
    changeCaptcha() {
      this.src = "/s/captcha/gen?rand=" + new Date();
    },
    backToSignIn() {
      this.findPwdShow = false;
      this.signInShow = true;
      this.signInUserName = "";
      this.signInPwd = "";
      this.signInLoading = false;
    },
    showErr(err) {
      this.$message.error(err);
    },
    showInfo(message) {
      this.$message.success(message);
    },
    trim(str) {
      return str.replace(/(^\s*)|(\s*$)/g, "");
    },
    confirmEmail() {
      this.signInShow = false;
      this.emailConfirmShow = true;
    },
    getQueryParameter(key) {
      var href = window.location.href;
      var reg = new RegExp("[?&]" + key + "=([^&#]*)", "i");
      var string = reg.exec(href);
      return string ? string[1] : null;
    }
  },
  components: {
    GButton
  }
};
</script>
<style lang="scss">
@import "common";

.sign-page {
  height: 100%;
  width: 100%;
  min-heigth: 350px;
  position: relative;
  overflow: hidden;
  font-family: PingFangSC-Regular;

  .footer-wrapper {
    width: 300px;
    margin: 0 auto;
    height: 10%;
    text-align: center;
    opacity: 0.7;
    color: #303c46;
    letter-spacing: 0;
    line-height: 14px;
    position: relative;
    font-size: 12px;
  }

  .tip {
    margin-bottom: 20px;
    color: $danger;
    font-size: 12px;
    padding-left: 20px;
  }

  .disabled {
    pointer-events: none;
    cursor: not-allowed;
    filter: alpha(opacity=65);
    -webkit-box-shadow: none;
    box-shadow: none;
    opacity: 0.65;
    -khtml-opacity: 0.65;
  }
  input {
    -webkit-appearance: none;
    -webkit-border-radius: 5px;
  }
  .input,
  .submit {
    display: block;
    width: 300px;
    height: 42px;
    background: #f9f9f9;
    margin: 0 auto 20px auto;
    border: 1px solid rgba(0, 24, 44, 0.15);
    border-radius: 5px;
  }
  .input,
  .verification-input {
    text-indent: 1em;
    font-size: 14px;
  }
  .submit {
    background: $darkPrimary;
    color: #fff;
    text-align: center;
    cursor: pointer;
  }
  .verification-wrapper {
    position: relative;
    display: block;
    width: 300px;
    margin: 0 auto 20px auto;
    height: 42px;

    .verification-input {
      height: 42px;
      width: 150px;
      float: left;
      margin-right: 10%;
      background: #f9f9f9;
      border: 1px solid rgba(0, 24, 44, 0.15);
      border-radius: 5px;
    }
    .verification-code {
      height: 42px;
      width: 120px;
      float: left;

      .img-captcha {
        cursor: pointer;
        height: 38px;
        width: 100%;
      }
    }
  }
  .wrong-input {
    border: 1px solid $danger;
  }
}

.sign-page .center-wrapper {
  width: 100%;
  position: relative;
  height: 85%;

  .logo-wrapper {
    margin: 0 auto;
    margin-top: 5%;
    position: relative;
    text-align: center;

    @media screen and (max-height: 1170px) {
      margin-top: 150px;
    }
    @media screen and (max-height: 970px) {
      margin-top: 100px;
    }
    @media screen and (max-height: 800px) {
      margin-top: 60px;
    }
    @media screen and (max-height: 600px) {
      margin-top: 30px;
    }

    .logo-img {
      width: 120px;
    }
  }

  .center-container {
    position: relative;
    width: 320px;
    height: 400px;
    margin: 0 auto;
    @media screen and (max-height: 1170px) {
      margin-top: 130px;
    }
    @media screen and (max-height: 970px) {
      margin-top: 80px;
    }
    @media screen and (max-height: 800px) {
      margin-top: 40px;
    }
    @media screen and (max-height: 600px) {
      margin-top: 20px;
    }

    .link-to-register {
      width: 300px;
      margin: 0 auto 20px auto;
      font-size: 12px;
      text-align: left;
      position: relative;
      a {
        cursor: pointer;
        color: $primary;
      }
      .link-toggle {
        position: absolute;
        right: 0;
        top: 0;
      }
    }

    .sign-in-wrapper {
      .sign-in-content {
        width: 100%;
        height: 100%;
      }
    }

    .register-wrapper {
      .register-content .agreement-wrapper {
        position: relative;
        display: block;
        width: 300px;
        margin: 0 auto 20px auto;
        font-size: 12px;

        a {
          color: #2090ff;
        }
      }
    }
    .find-pwd-wrapper {
      .back-to-sign-in {
        display: block;
        width: 300px;
        margin: 0 auto 30px auto;
        font-size: 12px;
        text-align: right;
        cursor: pointer;
        color: $primary;
      }
    }
  }
  .email-confirm-wrapper {
    height: 200px;
    width: 60%;
    min-width: 300px;
    margin: 0 auto;

    .email-confirm-content {
      margin-top: 50px;
      padding: 16px;
      background: $darkPrimary;
      width: 100%;
      height: 150px;
      color: #fff;
      .email-confirm-text {
        height: 85px;
      }

      .btn-wrapper {
        margin: 0 auto;
        width: 106px;
      }
    }
  }
}
</style>